# -*- coding: utf-8 -*-

import datetime

from flask import request, jsonify, abort, current_app, render_template
import markdown

from app.models import Product
from app.utils import wrap_h5, safe_int, wrap_response
from app.controllers import get_productsku_blackout_date


@current_app.route("/product/<product_id>/<category>/")
def product_info(product_id, category):
    """
    旅行产品详情页面
    """
    names = {
        'travel_time': u'行程时间表',
        'agreement': u'预定须知',
        'price_info': u'价格信息',
        'base_info': u'产品详情',
    }
    data = wrap_h5(request)
    product = Product.objects(pk=product_id).first()
    if not product:
        abort(404)
    category = 'agreement' if category == 'detail' else category
    md_content = getattr(product.product_display_info, category)
    html = markdown.markdown(md_content, extensions=['tables']) if md_content else ''
    data.update({
        'md_content': html,
        'title': names.get(category, product.name),
        'category': category,
    })
    return render_template('product/product_info.html', **data)


@current_app.route("/product/aticle/")
def product_article():
    """入口：订单页面的'接受本产品的服务条款'"""
    data = wrap_h5(request)
    product_id = request.args.get('product')
    product = None
    if product_id:
        product = Product.objects(pk=product_id, is_active=True).first()
    device_id = request.args.get('device_id', '')
    plan_id = request.args.get('plan_id', None)
    travel_date = request.args.get('travel_date', '')
    order_ids = request.args.get('order_ids', None)
    if order_ids:
        data['order_ids'] = order_ids
        data['plan_id'] = plan_id
        return render_template('product/product_article.html', **data)
    data.update({
        'product': product,
        'device_id': device_id,
        'plan_id': plan_id,
        'travel_date': travel_date,
        'order_id': request.args.get('order_id'),
    })
    return render_template('product/product_article.html', **data)


@current_app.route("/product/<product_id>/calendar/")
def product_calendar(product_id):
    """入口：订单页面的'使用日期'"""
    product = Product.objects(pk=product_id, is_active=True).first()
    device_id = request.args.get('device_id', '')

    now = datetime.datetime.now().strftime('%H:%M')
    today = datetime.date.today()
    print 'today', today

    k = 1 if product.start_time and \
        now > product.start_time else 0
    date = today + datetime.timedelta(days=safe_int(product.start_delta) + k)
    return render_template('product/product_calendar.html', **{
        'type_ids': request.args.get('type_ids', ''),  # 注：type_id即sku_id
        'today': str(today),
        'device_id': device_id,
        'default_date': date,
        'order_url': '/product/%s/order/' % product.pk,
        'product': product,
        'new': False,
        'is_breadtrip': False,
    })


@current_app.route("/product/<product_id>/calendar/events/")
def product_calendar_event(product_id):
    def convert2date(timestamp):
        try:
            t = int(timestamp)
            d = datetime.datetime.utcfromtimestamp(t)
            date = d.date()
        except:
            abort(404)
        return date

    result = []
    product = Product.objects(pk=product_id, is_active=True).first()
    start = convert2date(request.args.get('start'))
    type_ids = request.args.get('type_ids', [])  # 注：type_id即sku_id
    # ptypes = ProductType.objects.filter(is_active=True, product=product)
    skus = [sku for sku in product.productskus if sku.is_active]

    # 判断是否有产品类型id
    if type_ids:
        type_ids = type_ids.split(',')
        pks = []
        for type_id in type_ids:
            pk = type_id.split('_')[0]
            pks.append(pk)
        # _skus = skus.filter(pk__in=pks)
        # print 'pks', pks
        _skus = [sku for sku in skus if str(sku.pk) in pks]
        skus = _skus if _skus else skus
    result = get_productsku_blackout_date(skus, start=start)
    return wrap_response(result)
